﻿using Newtonsoft.Json;
using System;

namespace Signit.Sdk.Http.Webhook
{
    public class WebhookResponse : WebhookDataBase
    {
        public string RawData { get; set; }

        public AbstractWebhookResponse GetResponseData()
        {
            return JsonConvert.DeserializeObject(RawData, GetEventType()) as AbstractWebhookResponse;
        }

        public T GetResponseData<T>()
            where T : AbstractWebhookResponse
        {
            return JsonConvert.DeserializeObject<T>(RawData);
        }

        private Type GetEventType()
        {
            var @event = Event;
            var fullName = $"Signit.Sdk.Http.Webhook.{@event}";

            try
            {
                var type = Type.GetType(fullName, true, true);
                if (!typeof(AbstractWebhookResponse).IsAssignableFrom(type))
                {
                    throw new SignitException("无法根据事件名称[%s]自动生成对应的webhook响应数据[%s]，请选择重新解析方法");
                }
                return type;
            }
            catch (TypeLoadException tle)
            {
                throw new SignitException(
                    "无法根据事件名称[%s]自动生成对应的webhook响应数据[%s]，请选择重新解析方法",
                    tle);
            }
        }
    }
}
